package com.gnerv.rabbitmq.agent.service;

import com.gnerv.rabbitmq.agent.model.entity.ClusterConnection;
import com.gnerv.rabbitmq.agent.model.entity.Exchange;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Service
public class ExchangeService {

    @Resource
    private ConnectionService connectionService;

    public boolean createExchange(Exchange exchange, ClusterConnection clusterConnection) {
        Connection connection = connectionService.create(clusterConnection.getHostname(), clusterConnection.getPort(),
                clusterConnection.getUsername(), clusterConnection.getPassword(), exchange.getVhost());
        try (connection) {
            Channel channel = connection.createChannel(true);
            channel.exchangeDeclare(exchange.getName(), exchange.getType(), exchange.isDurable(), exchange.isAutoDelete(), exchange.isInternal(), exchange.getArguments());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            connection.close();
        }
        return true;
    }

}
